package com.lingshi.shopping_seckill_service.redis;

import cn.hutool.core.util.NumberUtil;
import com.lingshi.shopping.constant.RedisKey;
import com.lingshi.shopping.entity.CartGoods;
import com.lingshi.shopping.entity.Orders;
import com.lingshi.shopping.entity.SeckillGoods;
import com.lingshi.shopping.service.SecKillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.Order;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;


@Component
public class SecKillOrderExpireRedisListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SecKillService secKillService;

    public SecKillOrderExpireRedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        System.out.println("key = " + key);

        /**
         * 判断 key是否是订单号，是订单号才处理
         */
        //获取未过期的副本订单
        Orders orders = (Orders) redisTemplate.boundValueOps(key + "_copy").get();

        CartGoods cartGoods = orders.getCartGoods().get(0);


        BoundHashOperations bhos = redisTemplate.boundHashOps(RedisKey.SEC_KILL_GOODS);

        //获取redis中秒杀商品
        SeckillGoods redisCartGoods = (SeckillGoods)bhos.get(cartGoods.getGoodId().toString());

        //回退商品数量 : 现有数量+订单未支付过期数量
        redisCartGoods.setStockCount(redisCartGoods.getStockCount() + cartGoods.getNum());
        //保存到redis
        bhos.put(cartGoods.getGoodId().toString(), redisCartGoods);

        //删除副本key
        redisTemplate.delete(key + "_copy");

    }
}
